package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.OaOther;
import com.ruoyi.system.domain.OaProjectInitiation;
import com.ruoyi.system.domain.OaSupplierPayableSummary;
import com.ruoyi.system.mapper.OaProjectInitiationMapper;
import com.ruoyi.system.service.IOaProjectInitiationService;
import com.ruoyi.system.service.IOaSupplierPayableSummaryService;
import io.lettuce.core.ScriptOutputType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.OaOtheraPurchaseMapper;
import com.ruoyi.system.domain.OaOtheraPurchase;
import com.ruoyi.system.service.IOaOtheraPurchaseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 记录采购实际付款Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-12
 */
@Service
@Transactional
public class OaOtheraPurchaseServiceImpl implements IOaOtheraPurchaseService {
    @Autowired
    private OaProjectInitiationMapper oaProjectInitiationMapper;
    @Autowired
    private OaOtheraPurchaseMapper oaOtheraPurchaseMapper;
    @Autowired
    private IOaProjectInitiationService oaProjectInitiationService;
    @Autowired
    private IOaSupplierPayableSummaryService oaSupplierPayableSummaryService;

    /**
     * 查询记录采购实际付款
     *
     * @param id 记录采购实际付款主键
     * @return 记录采购实际付款
     */
    @Override
    public OaOtheraPurchase selectOaOtheraPurchaseById(Long id) {
        return oaOtheraPurchaseMapper.selectOaOtheraPurchaseById(id);
    }

    /**
     * 查询记录采购实际付款列表
     *
     * @param oaOtheraPurchase 记录采购实际付款
     * @return 记录采购实际付款
     */
    @Override
    public List<OaOtheraPurchase> selectOaOtheraPurchaseList(OaOtheraPurchase oaOtheraPurchase) {
        return oaOtheraPurchaseMapper.selectOaOtheraPurchaseList(oaOtheraPurchase);
    }


    /**
     * 新增记录采购实际付款
     *
     * @param oaOtheraPurchase 记录采购实际付款
     * @return 结果
     */
    @Override
    public int insertOaOtheraPurchase(OaOtheraPurchase oaOtheraPurchase) {
        if (oaOtheraPurchase.getPaymentAccount()==null||oaOtheraPurchase.getPaymentAccount().equals("")){
        throw    new RuntimeException("付款账户不能为空");
        }
        if (oaOtheraPurchase.getPaymentDate()==null){
            throw    new RuntimeException("付款时间不能为空");
        }
        oaOtheraPurchase.setPaymentAmount("0");
        // 根据采购实际付款的initiationId查询项目立项信息
        OaProjectInitiation oaProjectInitiation = oaProjectInitiationMapper.selectOaProjectInitiationById(Integer.valueOf(oaOtheraPurchase.getInitiationId()));
        if (oaProjectInitiation == null) {
            throw new RuntimeException("立项编号不存在");
        }
        if (oaOtheraPurchase.getInvoiceStatus().equals("是")) {
            oaOtheraPurchase.setInvoiceReview("1");
        } else {
            oaOtheraPurchase.setInvoiceReview("0");
        }
        if (oaOtheraPurchase.getIsAdditionalItem() == 1) {
//            oaProjectInitiation.setFinancialApproval("未审批");
            oaOtheraPurchase.setLiApprove("1");
            oaOtheraPurchase.setLiuApprove("1");
            oaOtheraPurchase.setPrincipalApprove("1");
        } else {
            oaOtheraPurchase.setLiApprove("0");
            oaOtheraPurchase.setLiuApprove("0");
            oaOtheraPurchase.setPrincipalApprove("0");
        }
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 如果采购实际付款的类型是供应商
        if (oaOtheraPurchase.getType().equals("供应商")) {
            // 如果当前用户不是项目负责人，则抛出异常
            if (loginUser.getUsername().equals(oaProjectInitiation.getInitiationPersonInCharge())
                    && loginUser.getUsername().equals("高琪")) {
                throw new RuntimeException("当前用户不是项目负责人 或高琪，无法填写");
            }
        }
        // 如果采购实际付款的类型是电商
        if (oaOtheraPurchase.getType().equals("电商")) {
            // 如果当前用户不是高琪，则抛出异常
            if (!loginUser.getUsername().equals("高琪")) {
                throw new RuntimeException("电商类请由高琪填写");
            }
        }
        // 设置采购实际付款的创建时间
        oaOtheraPurchase.setCreateTime(DateUtils.getNowDate());
        // 设置采购实际付款的填写人
        oaOtheraPurchase.setFiller(loginUser.getUsername());
        oaOtheraPurchase.setVerifiedAmount(BigDecimal.ZERO);
        if (oaOtheraPurchase.getInvoiceStatus().equals("未开")) {
            System.out.println("未开票");
            System.out.println(oaOtheraPurchase.getInvoicePrice());
            System.out.println(oaOtheraPurchase.getVerifiedAmount());
            System.out.println(oaOtheraPurchase.getVerifiedAmount().add(oaOtheraPurchase.getInvoicePrice()));
            oaOtheraPurchase.setVerifiedAmount(oaOtheraPurchase.getVerifiedAmount().add(oaOtheraPurchase.getInvoicePrice()));
        }
        int i = oaOtheraPurchaseMapper.insertOaOtheraPurchase(oaOtheraPurchase);
        accountsPayableSummary1(oaOtheraPurchase);
        //更新金额
        String initiationId = oaOtheraPurchase.getInitiationId();
        OaOtheraPurchase oaOther2 = new OaOtheraPurchase();
        oaOther2.setInitiationId(initiationId);
        List<OaOtheraPurchase> oaOthers1 = oaOtheraPurchaseMapper.selectOaOtheraPurchaseList(oaOther2);
        a(initiationId, oaOthers1);
        // 插入采购实际付款记录
        return i;
    }

    public void a(String initiationId, List<OaOtheraPurchase> oaOthers1) {
        OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.parseInt(initiationId));
        BigDecimal paidAmount = BigDecimal.ZERO;
        for (OaOtheraPurchase oaOther : oaOthers1) {
            paidAmount = paidAmount.add(oaOther.getActualPrice());
        }
        oaProjectInitiation.setTotalActualAmount(paidAmount);
        oaProjectInitiationService.updateOaProjectInitiation(oaProjectInitiation);
    }

    public void accountsPayableSummary1(OaOtheraPurchase purchase) {
        //判断同一立项有没有该供应商有则追加金额 没有则新增
        List<OaSupplierPayableSummary> list = Collections.emptyList();
        boolean a = false;
        OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(purchase.getInitiationId()));
        if (purchase.getType().equals("供应商")|| purchase.getType().equals("电商")) {
            OaSupplierPayableSummary oaSupplierPayableSummary = new OaSupplierPayableSummary();
            oaSupplierPayableSummary.setInitiationId(Long.valueOf(purchase.getInitiationId()));
            oaSupplierPayableSummary.setIsNumber(1L);
            oaSupplierPayableSummary.setSupplierName(purchase.getPurchaseTableSequence());
            list = oaSupplierPayableSummaryService.selectOaSupplierPayableSummaryByIdAndSupplier(oaSupplierPayableSummary);
        } else {
            //其他和零星采购拉过来
            a = true;
        }
        if (a) {
            //添加生成条件  1 增项的都审核完成 2 发票审核完成  遍历其他采购列表
            if (purchase.getInvoiceReview().equals("1") || purchase.getInvoiceReview().equals("3") ||
                    purchase.getLiApprove().equals("1") || purchase.getLiApprove().equals("3") ||
                    purchase.getLiuApprove().equals("1") || purchase.getLiuApprove().equals("3") ||
                    purchase.getPrincipalApprove().equals("1") || purchase.getPrincipalApprove().equals("3")
            ) {
                System.out.println("11");
            } else {
                System.out.println("22");
                //创建OaSupplierPayableSummary对象
                OaSupplierPayableSummary oaSupplierPayableSummary = new OaSupplierPayableSummary();
                //设置供应商名称
                oaSupplierPayableSummary.setSupplierName(purchase.getPurchaseTableSequence());
                //设置项目编号
                oaSupplierPayableSummary.setProjectNumber(oaProjectInitiation.getProjectNumber());
                //设置项目名称
                oaSupplierPayableSummary.setProjectName(oaProjectInitiation.getProjectContent());
                //设置报价金额
                oaSupplierPayableSummary.setQuotationAmount(purchase.getActualPrice());
                //设置结算金额
                oaSupplierPayableSummary.setSettlementAmount(purchase.getInvoicePrice());
                //设置负责人
                oaSupplierPayableSummary.setPersonInCharge(oaProjectInitiation.getInitiationPersonInCharge());
                //设置开始日期
                oaSupplierPayableSummary.setStartDate(oaProjectInitiation.getCommencementDate());
                //设置完成日期
                oaSupplierPayableSummary.setCompletionDate(oaSupplierPayableSummary.getCompletionDate());
                //判断项目是否完成
                if (oaProjectInitiation.getComplete() == 1) {
                    //设置项目完成状态为已完结
                    oaSupplierPayableSummary.setIsProjectCompleted("已完结");
                } else {
                    //设置项目完成状态为未完结
                    oaSupplierPayableSummary.setIsProjectCompleted("未完结");
                }
                oaSupplierPayableSummary.setIsNumber(2L);
                //设置发起id
                oaSupplierPayableSummary.setInitiationId(Long.valueOf(oaProjectInitiation.getId()));
                oaSupplierPayableSummary.setIsAmountSettled("未结清");
                oaSupplierPayableSummary.setOtheraPurchaseId(purchase.getId().toString());
                //插入应付汇总
                oaSupplierPayableSummaryService.insertOaSupplierPayableSummary(oaSupplierPayableSummary);
            }
            return;
        }
        if (list.isEmpty()) {
            //添加生成条件  1 增项的都审核完成 2 发票审核完成  遍历其他采购列表
            if (purchase.getInvoiceReview().equals("1") || purchase.getInvoiceReview().equals("3") ||
                    purchase.getLiApprove().equals("1") || purchase.getLiApprove().equals("3") ||
                    purchase.getLiuApprove().equals("1") || purchase.getLiuApprove().equals("3") ||
                    purchase.getPrincipalApprove().equals("1") || purchase.getPrincipalApprove().equals("3")
            ) {
                System.out.println("33");
            } else {
                System.out.println("44");
                //创建OaSupplierPayableSummary对象
                OaSupplierPayableSummary oaSupplierPayableSummary = new OaSupplierPayableSummary();
                //设置供应商名称
                oaSupplierPayableSummary.setSupplierName(purchase.getPurchaseTableSequence());
                //设置项目编号
                oaSupplierPayableSummary.setProjectNumber(oaProjectInitiation.getProjectNumber());
                //设置项目名称
                oaSupplierPayableSummary.setProjectName(oaProjectInitiation.getProjectContent());
                //设置报价金额
                oaSupplierPayableSummary.setQuotationAmount(purchase.getActualPrice());
                //设置结算金额
                oaSupplierPayableSummary.setSettlementAmount(purchase.getInvoicePrice());
                //设置负责人
                oaSupplierPayableSummary.setPersonInCharge(oaProjectInitiation.getInitiationPersonInCharge());
                //设置开始日期
                oaSupplierPayableSummary.setStartDate(oaProjectInitiation.getCommencementDate());
                //设置完成日期
                oaSupplierPayableSummary.setCompletionDate(oaSupplierPayableSummary.getCompletionDate());
                //判断项目是否完成
                if (oaProjectInitiation.getComplete() == 1) {
                    //设置项目完成状态为已完结
                    oaSupplierPayableSummary.setIsProjectCompleted("已完结");
                } else {
                    //设置项目完成状态为未完结
                    oaSupplierPayableSummary.setIsProjectCompleted("未完结");
                }
                //设置是否编号
                oaSupplierPayableSummary.setIsNumber(1L);
                //设置发起id
                oaSupplierPayableSummary.setInitiationId(Long.valueOf(oaProjectInitiation.getId()));
                oaSupplierPayableSummary.setIsAmountSettled("未结清");
                oaSupplierPayableSummary.setOtheraPurchaseId(purchase.getId().toString());
                //插入应付汇总
                oaSupplierPayableSummaryService.insertOaSupplierPayableSummary(oaSupplierPayableSummary);
            }
        } else {
            if (purchase.getInvoiceReview().equals("1") || purchase.getInvoiceReview().equals("3") ||
                    purchase.getLiApprove().equals("1") || purchase.getLiApprove().equals("3") ||
                    purchase.getLiuApprove().equals("1") || purchase.getLiuApprove().equals("3") ||
                    purchase.getPrincipalApprove().equals("1") || purchase.getPrincipalApprove().equals("3")
            ) {
                System.out.println("55");
            }else {
                System.out.println("66");
                OaSupplierPayableSummary oaSupplierPayableSummary = list.get(0);
                oaSupplierPayableSummary.setQuotationAmount(oaSupplierPayableSummary.getQuotationAmount().add(purchase.getActualPrice()));
                oaSupplierPayableSummary.setSettlementAmount(oaSupplierPayableSummary.getSettlementAmount().add(purchase.getInvoicePrice()));
                String originalIds = oaSupplierPayableSummary.getOtheraPurchaseId();
                String combinedIds = (originalIds != null ? originalIds + "," : "") + purchase.getId();
                // 使用HashSet去重
                Set<String> uniqueIds = new HashSet<>(Arrays.asList(combinedIds.split(",")));
                // 过滤掉空字符串（如果存在）并重新拼接
                String newIds = String.join(",", uniqueIds.stream()
                        .filter(id -> !id.isEmpty())
                        .collect(Collectors.toList()));
                // 设置回对象
                oaSupplierPayableSummary.setOtheraPurchaseId(newIds);
                oaSupplierPayableSummaryService.updateOaSupplierPayableSummary(oaSupplierPayableSummary);
            }
        }

    }

    /**
     * 修改记录采购实际付款
     *
     * @param oaOtheraPurchase 记录采购实际付款
     * @return 结果
     */
    @Override
    public int updateOaOtheraPurchase(OaOtheraPurchase oaOtheraPurchase) {
        int i = oaOtheraPurchaseMapper.updateOaOtheraPurchase(oaOtheraPurchase);
        String initiationId = oaOtheraPurchase.getInitiationId();
        OaOtheraPurchase oaOther2 = new OaOtheraPurchase();
        oaOther2.setInitiationId(initiationId);
        List<OaOtheraPurchase> oaOthers1 = oaOtheraPurchaseMapper.selectOaOtheraPurchaseList(oaOther2);
        a(initiationId, oaOthers1);
        return i;
    }

    /**
     * 批量删除记录采购实际付款
     *
     * @param ids 需要删除的记录采购实际付款主键
     * @return 结果
     */
    @Override
    public int deleteOaOtheraPurchaseByIds(Long[] ids) {
        OaOtheraPurchase oaOtheraPurchase = null;
        for (Long id : ids) {
            oaOtheraPurchase = oaOtheraPurchaseMapper.selectOaOtheraPurchaseById(id);
        }
        int i = oaOtheraPurchaseMapper.deleteOaOtheraPurchaseByIds(ids);
        String initiationId = oaOtheraPurchase.getInitiationId();
        OaOtheraPurchase oaOther2 = new OaOtheraPurchase();
        oaOther2.setInitiationId(initiationId);
        List<OaOtheraPurchase> oaOthers1 = oaOtheraPurchaseMapper.selectOaOtheraPurchaseList(oaOther2);
        a(initiationId, oaOthers1);
        return i;
    }

    /**
     * 删除记录采购实际付款信息
     *
     * @param id 记录采购实际付款主键
     * @return 结果
     */
    @Override
    public int deleteOaOtheraPurchaseById(Long id) {
        OaOtheraPurchase oaOtheraPurchase = oaOtheraPurchaseMapper.selectOaOtheraPurchaseById(id);
        int i = oaOtheraPurchaseMapper.deleteOaOtheraPurchaseById(id);
        String initiationId = oaOtheraPurchase.getInitiationId();
        OaOtheraPurchase oaOther2 = new OaOtheraPurchase();
        oaOther2.setInitiationId(initiationId);
        List<OaOtheraPurchase> oaOthers1 = oaOtheraPurchaseMapper.selectOaOtheraPurchaseList(oaOther2);
        a(initiationId, oaOthers1);
        return i;
    }

    @Override
    public void delete(Integer id) {
        oaOtheraPurchaseMapper.delete(id);
    }

    @Override
    public List<OaOtheraPurchase> selectOaOtheraPurchaseList2(OaOtheraPurchase queryPurchase) {
        return oaOtheraPurchaseMapper.selectOaOtheraPurchaseList2(queryPurchase);
    }
}
